/***** BEGIN LICENSE BLOCK *****
 Version: MPL 1.1
 
 The contents of this file are subject to the Mozilla Public License Version 
 1.1 (the "License"); you may not use this file except in compliance with 
 the License. You may obtain a copy of the License at 
 http://www.mozilla.org/MPL/
 
 Software distributed under the License is distributed on an "AS IS" basis,
 WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 for the specific language governing rights and limitations under the
 License.
 
 The Original Code is GureGipuzkoa Extension.
 
 The Initial Developer of the Original Code is Asier Sarasua Garmendia.
 Portions created by the Initial Developer are Copyright (C) 2009
 the Initial Developer. All Rights Reserved.
 
 Contributor(s):
    Asier Sarasua Garmendia <asier.sarasua@gmail.com>
    Julen Ruiz Aizpuru <julenx@gmail.com>
    Juanan Pereira Varela <juanan@diariolinux.com>
 
 ***** END LICENSE BLOCK *****/


const ggPhotos = {
 
  populateTree:
    function(obj, value) {
      var aTree = document.getElementById("gg-result-list");
      var aTreechild = document.getElementById("gg-result-ch");
      var chkTitle = gureGipuzkoaUtils.prefManager.getBoolPref("guregipuzkoa.title.checked");
      var chkTag = gureGipuzkoaUtils.prefManager.getBoolPref("guregipuzkoa.tag.checked");
      var schMine = gureGipuzkoaUtils.prefManager.getBoolPref("guregipuzkoa.mine.selected");
      var perPage = gureGipuzkoaUtils.prefManager.getIntPref("guregipuzkoa.page.photocount");
      var pageNum = gureGipuzkoaUtils.prefManager.getIntPref("guregipuzkoa.page.currentpage");
      var userId = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.id");
      var value1 = value;
      var value2 = "";
      
      if (gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.apikey") == "") {
        gureGipuzkoaUIUtils.prompt.alert(null,
                               gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                               gureGipuzkoaStrUtils.strBundle.getString("APINo"));
        gureGipuzkoa.openHelp("chrome://guregipuzkoa/locale/help/apikey.html");
        return false;
      }
      if (value=="") {
        var msg = gureGipuzkoaStrUtils.strBundle.getString("EnterText");
        gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"), msg);
        return;
      }
      if (!chkTitle&&!chkTag) {
        msg = gureGipuzkoaStrUtils.strBundle.getString("CheckSearch");
        gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"), msg);
        return;
      }
      if ((userId == "")&&(schMine == true)) {
        gureGipuzkoaUIUtils.prompt.alert(null,
                               gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                               gureGipuzkoaStrUtils.strBundle.getString("SearchNoUser"));
        ggAccounts.onLogin();
      }
      if (userId == "") {
        return false;
      }
      if (chkTitle) {
        value2 = value;
        value1 = "";
      }
      if (obj.id == "gg-next-page") {
        pageNum = pageNum + 1;
      } else if (obj.id == "gg-prev-page") {
        pageNum = pageNum - 1;
      } else {
        pageNum = 1;
      }
      gureGipuzkoaUtils.prefManager.setIntPref("guregipuzkoa.page.currentpage", pageNum);
      if(!schMine) {
        userId = "";
      }

      //Wait cursor
      document.getElementById("ggSidebar").setAttribute('wait-cursor', true);

      //XMLHttpRequest
      gureGipuzkoa.apiCall(
        {method: 'gg.photos.search', 'tags': value1, 'text': value2, 'page': pageNum, 'per_page': perPage, 'user_id': userId},
        function(xhr) {
          var userLang = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.lang.default");
          //Set labels visible
          document.getElementById("gg-thumb").collapsed = false;
          document.getElementById("gg-thumb-title").collapsed = false;
          document.getElementById("gg-thumb-author").collapsed = false;
          document.getElementById("gg-thumb-desc").collapsed = false;
          document.getElementById("gg-thumb-image").collapsed = false;

          aTree.view.selection.select(-1);  //Workaround to prevent issue #18: http://code.google.com/p/guregipuzkoa/issues/detail?id=18

          //First, remove all the children of the tree
          while (aTreechild.firstChild) {
            aTreechild.removeChild(aTreechild.firstChild);
          }
    
          var nPhotos = xhr.responseXML.getElementsByTagName("photo");
   
          if (nPhotos[0] == null) {
            document.getElementById("gg-prev-page").disabled = true;
            document.getElementById("gg-next-page").disabled = true;
            document.getElementById("gg-current-page").value = "";
            var it = document.createElement("treeitem");
            aTreechild.appendChild(it);
            var rw = document.createElement("treerow");
            it.appendChild(rw);
            var cl1 = document.createElement("treecell");
            rw.appendChild(cl1);
            msg = gureGipuzkoaStrUtils.strBundle.getString("NoSearch");
            cl1.setAttribute('label', msg);
            document.getElementById("gg-thumb").collapsed = true;
            document.getElementById("ggSidebar").removeAttribute('wait-cursor'); //Remove wait cursor
            return;
          }
    
          for (var i = 0; i < nPhotos.length; i++) {
            var aLink = nPhotos[i].attributes[0].value;
            var aTitle = nPhotos[i].attributes[1].value;
            if (aTitle == "") {
              aTitle = gureGipuzkoaStrUtils.strBundle.getString("NoTitle");
            }
            if (aTitle.indexOf("|") != -1) {
              if (userLang == "es") {
                aTitle = aTitle.split("|")[0];
              } else {
                aTitle = aTitle.split("|")[1];
              }
            }
            var it = document.createElement("treeitem");
            aTreechild.appendChild(it);
            var rw = document.createElement("treerow");
            it.appendChild(rw);
            var cl1 = document.createElement("treecell");
            rw.appendChild(cl1);
            cl1.setAttribute('label', aTitle);
            var cl2 = document.createElement("treecell");
            rw.appendChild(cl2);
            cl2.setAttribute('label', aLink);
          }
   
          //Pagination
          var numPhotos = xhr.responseXML.getElementsByTagName("photos")[0];
          var aPrev = document.getElementById("gg-prev-page");
          var aNext = document.getElementById("gg-next-page");
          var aCurrent = document.getElementById("gg-current-page");
          gureGipuzkoaUIUtils.paginate(numPhotos.attributes[1].value, numPhotos.attributes[2].value, aPrev, aNext, aCurrent); 

          aTree.focus();
          aTree.view.selection.select(0);
        },
        function() {});
      },


  openImage:        //Open image in a tab when double clicking the thumbnail or the tree value
    function() {
      var aTree = document.getElementById("gg-result-list");
      var selection = aTree.view.selection;
      //Change this
      var aUrl = gureGipuzkoa.photoURL+
                 aTree.view.getCellText(aTree.currentIndex, aTree.columns.getColumnAt(1));
      gureGipuzkoaUIUtils.useTab(aUrl);
      aTree.focus();
    },


  loadImage:        //Load thumbnail in the image and texts (author, title, description) in the labels 
    function() {
      if (gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.apikey") == "") {
        gureGipuzkoaUIUtils.prompt.alert(null,
                               gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                               gureGipuzkoaStrUtils.strBundle.getString("APINo"));
        gureGipuzkoa.openHelp("chrome://guregipuzkoa/locale/help/apikey.html");
        return false;
      }
      document.getElementById("ggSidebar").setAttribute('wait-cursor', true); //Wait cursor
      var userLang = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.lang.default");
      if(userLang == "eu") {
        var altLang = "es";
      } else {
        var altLang = "eu";
      }

      var aTree = document.getElementById("gg-result-list");
      var aImage = document.getElementById("gg-thumb-image");
      aImage.src = "";
      var titleLabel = document.getElementById("gg-thumb-title");
      var authorLabel = document.getElementById("gg-thumb-author");
      var descLabel = document.getElementById("gg-thumb-desc");
      var selection = aTree.view.selection;
      var numUrl = aTree.view.getCellText(aTree.currentIndex, aTree.columns.getColumnAt(1));

      //Clear labels
      titleLabel.value = "";
      authorLabel.value = "";
      descLabel.value = "";

      //XMLHttpRequest
      gureGipuzkoa.apiCall(
        {method: 'gg.photos.getInfo', photo_id: numUrl},
        function(xhr) {
          var aUrl = xhr.responseXML.getElementsByTagName("url")[0].firstChild.data;
          aUrl = aUrl.replace(/original/, "medium");
          aImage.src = aUrl;

          try {
            var aTitleObj = xhr.responseXML.getElementsByTagName("title_"+userLang)[0].firstChild;
            var aTitle = aTitleObj.data;
          } catch(e) {
            if (aTitleObj == null) {
              var aTitle = xhr.responseXML.getElementsByTagName("title_"+altLang)[0].firstChild.data;
            } else {
              var aTitle = aTitleObj.data;
            }
          }
          titleLabel.value = aTitle;

          var aAuthor = xhr.responseXML.getElementsByTagName("photo")[0].attributes[9].value;
          authorLabel.value = aAuthor;

          try {
            var aDescObj = xhr.responseXML.getElementsByTagName("description_"+userLang)[0].firstChild;
            var aDesc = aDescObj.data;
          } catch(e) {
            if (aDescObj == null) {
              var aDesc = xhr.responseXML.getElementsByTagName("description_"+altLang)[0].firstChild.data;
            } else {
              var aDesc = aDescObj.data;
            }
          }
          descLabel.value = aDesc;

        },
        function() {});
      },


  resizeImage:          // Resize thumbnails
    function(imageID) {
      var aSize = gureGipuzkoaUtils.prefManager.getIntPref("guregipuzkoa.thumbnail.thumbsize");
      var image = document.getElementById(imageID);
      var imageSRC = image.src;
      var img = new Image();
      img.src = imageSRC;
      if(img.height > aSize) {
        var maxh = aSize;
        var iScale = (100 * maxh)/img.height;
        var wScale = (img.width * iScale) / 100;
        var hScale = maxh;
        image.style.width = wScale+"px";
        image.style.height = hScale+"px";
      } else {
        image.style.width = img.width+"px";
        image.style.height = img.height+"px";
      }
      //Remove wait cursor
      document.getElementById("ggSidebar").removeAttribute('wait-cursor');
    },


}
